from fastapi import APIRouter, Query,UploadFile
from pandas.plotting import table
from tortoise.expressions import Q
from tortoise.functions import Sum
from app.controllers.saas.consumables import consumables_controller
from app.controllers.system.user import user_controller
from app.core.ctx import CTX_USER_ID
from app.core.dependency import DependCustomerAuth
from app.models import ConsumablesUse
from app.schemas.base import Success, SuccessExtra,Fail
from app.schemas.saas import *
from app.settings.config import settings
from datetime import datetime, timedelta
import calendar

saas_consumables_router = APIRouter()
model_name = "耗材基础信息"


@saas_consumables_router.get("/list", summary=f"查看{model_name}列表", dependencies=[DependCustomerAuth])
async def do_settings_list(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
        name: str = Query(None, description=f"{model_name}名称"),
        tongji: int = Query(0, description="是否计算合计消耗"),
        start_time: str = Query(None, description=f"统计开始时间"),
):
    q = Q()
    user_id = CTX_USER_ID.get()
    user = await user_controller.get(user_id)
    # if user.space_id:
    #     q &= Q(space_id__in=user.space_id)
    if name:
        q &= Q(name__contains=name)
    total, data = await consumables_controller.do_list(page=page, page_size=page_size, search=q)
    for item in data:
        item["type_name"] = settings.SAAS_CONSUMABLES_TYPE[item["type"] ]
        if tongji == 1:
            all_use = await get_all_use(item["id"], start_time,user.space_id)
            item["used"] = all_use

    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)

async def get_all_use(consumables_id:int,start_time:str,space_id):
    if start_time:
        dt = datetime.strptime(start_time, '%Y-%m-%d %H:%M:%S')
        # 获取当月最后一天的日期
        _, last_day = calendar.monthrange(dt.year, dt.month)
        end_time = datetime(dt.year, dt.month, last_day, 23, 59, 59)
    else:
        # 当前时间
        now = datetime.now()
        start_time = datetime(now.year, now.month, 1, 0, 0, 0)
        _, last_day = calendar.monthrange(now.year, now.month)
        end_time = datetime(now.year, now.month, last_day, 23, 59, 59)

    result = await ConsumablesUse.filter(
        consumables_id=consumables_id,
        created_at__range=(start_time, end_time),
        space_id__in=space_id
    ).annotate(total=Sum('nums')).first()

    if result and result.total is not None:  # 检查是否存在且非 None
        total = float(result.total)
    else:
        total = 0.0  # 默认值

    return total

@saas_consumables_router.get("/get", summary=f"查看{model_name}")
async def do_settings_get(
        data_id: int = Query(..., description="ID"),
):
    data = await consumables_controller.do_detail(data_id=data_id)
    return Success(data=data)

@saas_consumables_router.post("/create", summary=f"创建{model_name}")
async def do_settings_create(
        data_in: ConsumablesCreate,
):
    await consumables_controller.do_create(obj_in=data_in)
    return Success(msg="创建成功")

@saas_consumables_router.post("/update", summary=f"更新{model_name}")
async def do_settings_update(
        data_in: ConsumablesUpdate,
):
    await consumables_controller.do_update(obj_in=data_in)
    return Success(msg="更新成功")

@saas_consumables_router.delete("/delete", summary=f"删除{model_name}")
async def do_settings_delete(
        data_id: int = Query(..., description="ID"),
):
    await consumables_controller.do_delete(data_id=data_id)
    return Success(msg="删除成功")

@saas_consumables_router.get("/type", summary=f"获取{model_name}分类")
async def list_level():
    level_objs = settings.SAAS_CONSUMABLES_TYPE
    data = []
    key = 0
    for level in level_objs:
        if level:
            data.append({"name":level,"id":key})
        key += 1
    return Success(data=data)